﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

using DFYE.Web.Models;
using JULONG.WEB.Library;
using System.Text.RegularExpressions;
using System.Web.Helpers;

namespace DFYE.Web.Areas.manage.Controllers
{
    public class documentController : Controller
    {
        DataSession<entityDBContainer, document> db = new DataSession<entityDBContainer, document>();
        DataSession<entityDBContainer, documentType> dbType = new DataSession<entityDBContainer, documentType>();

        public documentController()
        {
            ViewBag.type = typeSelect();
        }

        //
        // GET: /manage/product/
        public ActionResult Index(int? id)//id为类别
        {
            var entity = dbType.query().FirstOrDefault(d => d.ID == id);
            if (entity == null) entity = dbType.query().FirstOrDefault();
            ViewData.Model = entity;

            return View();
        }

        //
        // GET: /manage/product/Create
        public ActionResult Create(int? id)//id为类别
        {
            if (!dbType.query().Any(d => d.ID == id)) throw new Exception("无此类型！");
            var entity = db.create();
            entity.documentTypeID = id.Value;
            entity.able = true;
            ViewData.Model = entity;
            return View();
        }

        //
        // POST: /manage/product/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(FormCollection collection)
        {
            var entity = db.create();
            try
            {
                UpdateModel(entity);
                entity.datetime = DateTime.Now;
                entity.ext = Makethumbnail(entity.content);
                db.insert(entity);

                
                
                return RedirectToAction("Index","document/index/"+ collection.GetValue("documentTypeID").AttemptedValue);
            }
            catch(Exception e)
            {
                ViewData.Model = entity;
                return View();
            }
        }
        [NonAction]
        private string Makethumbnail (string str){
            Regex regImg = new Regex(@"\<img.*?\>", RegexOptions.IgnoreCase);
            Regex regSrc = new Regex(@"(?<=src="").*?(?="")", RegexOptions.IgnoreCase);
            
            // 搜索匹配的字符串            
            MatchCollection matches = regImg.Matches(str);

            if (matches.Count < 0) {
                return null;
            }

            List<string> sUrlList = new List<string>();
            string appAbsPath = AppDomain.CurrentDomain.BaseDirectory;
            string thumbnailPath = @"\thumbnail\";

            string imagePath;
            // 取得匹配项列表            
            foreach (Match match in matches)
            {
                
                imagePath = regSrc.Match(match.Value).Value;

                WebImage webimage = new WebImage(appAbsPath + imagePath);

                string _fileName = Path.GetFileName(webimage.FileName);
                string _filePath = Path.GetDirectoryName(webimage.FileName);

                if (webimage.Width > 160)
                {
                    webimage.Resize(160, 120,true,true);
                    
                    if (!Directory.Exists(_filePath + thumbnailPath)) {
                        Directory.CreateDirectory(_filePath + thumbnailPath);
                    }

                    webimage.Save(_filePath + @"\thumbnail\" + _fileName);
                    sUrlList.Add(_fileName);
                }
                
                //_fileInfo = new FileInfo(AppDomain.CurrentDomain.
            }



            return String.Join(",",sUrlList);
        }

        public ActionResult Edit(int id)
        {
            ViewData.Model = db.get(d => d.ID == id);
            return View();
        }

        //
        // POST: /manage/product/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            var entity = db.get(d => d.ID == id);

            try
            {
                UpdateModel(entity);
                entity.ext = Makethumbnail(entity.content);
                db.save();
                
                return RedirectToAction("Index", "document/index/" + collection.GetValue("documentTypeID").AttemptedValue);
            }
            catch(Exception e)
            {
                ViewData.Model = entity;
                return View();
            }
        }

        //
        // GET: /manage/product/Delete/5
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
                db.delete(d => d.ID == id);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [NonAction]
        public Dictionary<int, string> typeSelect()
        {
            return dbType.query().ToDictionary(d => d.ID, d => d.name);
        }
    }
}
